package sample.plugin.editor.activation.view;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;

import com.qiplat.open.ui.util.DensityUtils;

import java.util.LinkedList;

import io.github.rosemoe.sora.event.ContentChangeEvent;
import io.github.rosemoe.sora.event.EventReceiver;
import io.github.rosemoe.sora.event.Unsubscribe;
import io.github.rosemoe.sora.widget.CodeEditor;

/**
 * Modified by Tiecode Project Team
 * Origin: https://github.com/covetcode/EditTextFirework-Demo/edit/master/edittextfirework/src/main/java/com/wayww/edittextfirework/FireworkView.java
 */
public class FireworkView extends View {

    private CodeEditor bindTarget;
    private final LinkedList<Firework> fireworks = new LinkedList<>();
    private int windSpeed;

    public FireworkView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public FireworkView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FireworkView(Context context) {
        super(context);
    }

    public void bind(CodeEditor editor) {
        this.bindTarget = editor;
        editor.subscribeEvent(ContentChangeEvent.class, new EventReceiver<ContentChangeEvent>() {
            @Override
            public void onReceive(ContentChangeEvent event, Unsubscribe unsubscribe) {
                int line = event.getChangeStart().line;
                int column = event.getChangeStart().column;
                float x = editor.getCharOffsetX(line, column);
                float y = editor.getCharOffsetY(line, column) + DensityUtils.dipToPx(editor.getContext(), 100);
                launch(x, y, event.getAction() == ContentChangeEvent.ACTION_INSERT ? 1 : -1);
            }
        });
    }

    public void removeBind(){
        bindTarget = null;
    }

    private void launch(float x, float y, int direction){
        final Firework firework = new Firework(new Firework.Location(x, y), direction);
        firework.addAnimationEndListener(new Firework.AnimationEndListener() {
            @Override
            public void onAnimationEnd() {
                //动画结束后把firework移除，当没有firework时不会刷新页面
                fireworks.remove(firework);
            }
        });
        fireworks.add(firework);
        firework.fire();
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        for (int i =0 ; i<fireworks.size(); i++){
            fireworks.get(i).draw(canvas);
        }
        if (fireworks.size()>0)
            invalidate();
    }

}
